//裸钻新增和编辑页面

var RATE=Number($.cookie("DiasRate"));
var EDITMODE=false;
var i_rapnet="";
var TYPE=0;//类型 
//时间的
var calendarDateFormat = myApp.calendar({
    input: '#data_ShipTime',
    monthNames: ['01'+_(''+_('月')), '02'+_('月'), '03'+_('月'), '04'+_('月'), '05'+_('月'), '06'+_('月'), '07'+_('月'), '08'+_('月') , '09'+_('月') , '10'+_('月'), '11'+_('月'), '12'+_('月')],
    dayNamesShort: [_('日'), _('一'), _('二'), _('三'), _('四'), _('五'), _('六')],
    closeOnSelect:true,
});
var calendarDateFormat = myApp.calendar({
    input: '#data_PurchaseTime',
    monthNames: ['01'+_(''+_('月')), '02'+_('月'), '03'+_('月'), '04'+_('月'), '05'+_('月'), '06'+_('月'), '07'+_('月'), '08'+_('月') , '09'+_('月') , '10'+_('月'), '11'+_('月'), '12'+_('月')],
    dayNamesShort: [_('日'), _('一'), _('二'), _('三'), _('四'), _('五'), _('六')],
    closeOnSelect:true,
});
var calendarDateFormat = myApp.calendar({
    input: '#data_ArrivalTime',
    monthNames: ['01'+_(''+_('月')), '02'+_('月'), '03'+_('月'), '04'+_('月'), '05'+_('月'), '06'+_('月'), '07'+_('月'), '08'+_('月') , '09'+_('月') , '10'+_('月'), '11'+_('月'), '12'+_('月')],
    dayNamesShort: [_('日'), _('一'), _('二'), _('三'), _('四'), _('五'), _('六')],
    closeOnSelect:true,
});
(function(){
    var addForm={
        init:function(){
            this.bindEvents();
            this.loadCommon();
            getRecommend();
        },
        bindEvents:function(){
            var self=this;
            $("#rate").text(RATE);
            //编辑
            args = GetUrlParms();
            if(args["ID"]!=undefined){
                ID = args["ID"];//产品ID
                EDITMODE=true;
            }
            //页面顶部显示的title
            if(EDITMODE){
                $(".category").hide();
                self.bindData(ID);
                $("#page_title").html(_("裸钻编辑"));

            }else{
                $("#page_title").html(_("裸钻新增"));
                $(".category").show();
            }
            //修改新增：采购人
            var html_purchaseAgent = "";
            if (list.msgcode ==true) {
                for(var k in list.msginfo){
                    html_purchaseAgent +='<option value="'+k+'">'+ _(list.msginfo[k]) +'</option>';
                }
            }
            else {
                html_purchaseAgent += "<option></option>";
            }
            $("#purchaseAgent").append(html_purchaseAgent);
            //切换主石类型
            self.changType(0);
            $("#data_category").on("click","span",function(){
                $(this).addClass("active").siblings().removeClass("active");
                TYPE=$("#data_category span.active").attr("data-value");
                self.changType(TYPE);
                self.IsFancyType(TYPE);//显示彩钻参数;

            });
            //关闭弹框
            $("#close_tip_btn").on("click",function(){
                $("#tip_box").hide();
            });
            //原的改变 的计算
            $("#sourceDolarPerGrain").keyup(function () {//原$
                CalcAllBySourceDolarPerGrain("sourceDiscountReturn", "origin_rmb_price", "sourceDolarPerGrain", "sourceDolarPerCarat", "SaleseRate", "_rapnet", "form_Weight",1);
            });
            $("#form_data").on("keyup","#sourceDiscountReturn",function () {//退点
                CalcAllByDiscountReturn("sourceDiscountReturn", "origin_rmb_price", "sourceDolarPerGrain", "sourceDolarPerCarat", "SaleseRate", "_rapnet", "form_Weight",1);
            });
            $("#origin_rmb_price").on("keyup",function(){//原￥
                CalcAllBySourceRmbGrain("sourceDiscountReturn", "origin_rmb_price", "sourceDolarPerGrain", "sourceDolarPerCarat", "SaleseRate", "_rapnet", "form_Weight",1);
            });
            $("#origin_rmb_per_price").on("keyup",function(){//原￥/ct
                CalcAllByRMBPerPrice("sourceDiscountReturn", "origin_rmb_price", "sourceDolarPerGrain", "sourceDolarPerCarat", "SaleseRate", "_rapnet", "form_Weight",1);
            });
            $("#sourceDolarPerCarat").on("keyup",function(){//原$/ct
                CalcAllByUSDPerPrice("sourceDiscountReturn", "origin_rmb_price", "sourceDolarPerGrain", "sourceDolarPerCarat", "SaleseRate", "_rapnet", "form_Weight",1);
            });
            //采的变化计算
            $("#purchaseUSDPerGrain").keyup(function () {//采$
                CalcAllBySourceDolarPerGrain("purchaseDiscountReturn", "purchaseRMB", "purchaseUSDPerGrain", "purchaseUSDPerCarat", "purchaseExchange", "_rapnet", "form_Weight",2);
            });
            $("#purchaseUSDPerCarat").on("keyup",function(){//采$/ct
                CalcAllByUSDPerPrice("purchaseDiscountReturn", "purchaseRMB", "purchaseUSDPerGrain", "purchaseUSDPerCarat", "purchaseExchange", "_rapnet", "form_Weight",2);
            });
            $("#form_data").on("keyup","#purchaseDiscountReturn",function () {//才退点
                CalcAllByDiscountReturn("purchaseDiscountReturn", "purchaseRMB", "purchaseUSDPerGrain", "purchaseUSDPerCarat", "purchaseExchange", "_rapnet", "form_Weight",2);
            });
            $("#purchaseRMB").keyup(function () {
                CalcAllBySourceRmbGrain("purchaseDiscountReturn", "purchaseRMB", "purchaseUSDPerGrain", "purchaseUSDPerCarat", "purchaseExchange", "_rapnet", "form_Weight",2);
            });
            $("#form_data").on("keyup","#purchaseExchange",function () {
                $("#purchaseRMB").val(formatRMBPrice(Number($("#purchaseUSDPerGrain").val()) * Number($("#purchaseExchange").val())));
            });
            //改变重量、颜色、净度和形状，相应的白钻价格会改变
            $("#form_Weight,#data_color,#data_clarity,#data_shape").on("change",function(){
                var val=self.validateWeight();
                if(val==true && TYPE==0){
                    self.getrapnet();
                }
                if($("#sourceDiscountReturn").val()!="" && TYPE==0){
                    CalcAllByDiscountReturn("sourceDiscountReturn", "sourceRmbGrain", "_OriginUSDPerGrain ", "sourceDolarPerCarat ", "SaleseRate", "_rapnet", "form_Weight");
                }
                if($("#purchaseDiscountReturn").val()!="" && TYPE==0){
                    CalcAllByDiscountReturn("purchaseDiscountReturn", "_PurchaseRMB", "_PurchaseUSDPerGrain", "_PurchaseUSDPerCarat", "_PurchaseExchange", "_rapnet", "form_Weight");
                }
            });

            //提交验证
            $("#submit_btn").on("click",function(){
                $("#form_data").submit();
            });
            $("#reset_btn").on("click",function(){
                if(EDITMODE){
                    myApp.alert(_("编辑时不能重置参数！"));
                }else{
                    $("#form_data")[0].reset();
                }
            });
            var aValidate = $("#form_data").validate({
                debug: true, //调试模式取消submit的默认提交功能
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应
                onkeyup: false,
                focusInvalid:true,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                    self.addProduct();
                },
                rules: {
                    OriginSN: "required",
                    Weight: "required",
                    Status: "required",
                    CertType: "required",
                    OriginUSDPerGrain : {
                        required: true,
                        max: 1000000000
                    },
                    SourceDiscountReturn:"required",
                    SourceDolarPerGrain:"required",
                },
                messages: {
                    OriginSN: "",
                    Weight: "",
                    Status:"",
                    CertType:"",
                    OriginUSDPerGrain : {
                        required:"",
                        max: _("价格必须小于9位数")
                    },
                    SourceDiscountReturn:"",
                    SourceDolarPerGrain:"",
                }
            });

        },
        //彩钻下的参数
        IsFancyType:function(type){
            if(type==0){
                $(".fancy_no").show();
            }else{
                $(".fancy_no").hide();
            }
        },
        //新增时验证重量是否已填
        validateWeight:function(){
            if($("#form_Weight").val()=="" || $("#form_Weight").val()<=0 ){
                myApp.alert(_("请先输入重量！"));
                return false;
            }else{
                return true;
            }
        },
        //获取rapnet值来计算价格
        getrapnet:function() {
            var param = {};
            param.Weight = $("#form_Weight").val();
            param.Color = $("#data_color").val();
            param.Clarity = $("#data_clarity").val();
            param.Shape = $("#data_shape").val();
            $.ajax({
                url: "/Team/GetRapnetByParam",//提交地址
                type: "Post",//提交方式
                data:JSON.stringify(param),
                async:false,
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    result = JSON.parse(result);
                    if (result.result) {
                        i_rapnet = result.message;
                    }
                }
            });
        },
        //编辑时绑定数据
        bindData:function(ID){
            myApp.showIndicator();//显示加载中
            var self=this;
            var submitJson={};
            submitJson.InventoryID=ID;
            $.ajax({
                url:'/Team/GetInventoryInfo',
                type:'POST',
                data: JSON.stringify(submitJson),
                dataType:'JSON',
                contentType: "application/json; charset=utf8",
                success:function(result){
                    var data=eval('(' + result + ')')
                    self.changType(data.IsFancy);//切换
                    self.IsFancyType(data.IsFancy);
                    data.CertType=data.CertType.toUpperCase();
                    $("#data_category").find("span").eq(data.IsFancy).addClass("active").siblings().removeClass("active");//类型的绑定
                    $("#form_data").setForm(data);//帮数据

                    var DiaRate=Number($.cookie("DiasRate"));//销售汇率
                    var DiaPurchaseExchangerate=Number($.cookie("DiaPurchaseExchangerate"));//采购汇率
                    $("#origin_rmb_price").val(formatRMBPrice(Number(data.SourceDolarPerGrain)*DiaRate));//原人民币
                    $("#origin_rmb_per_price").val(formatRMBPrice(Number(data.SourceDolarPerCarat)*DiaRate));//原人民币/CT
                    $("#id_input").prop({"name":"ID","value":data.InventoryID});//ID
                    if(data.PurchaseExchange==0 || data.PurchaseExchange==null){
                        var _purchaseRMB=Number(data.PurchaseUSDPerGrain)*DiaPurchaseExchangerate;
                        $("#purchaseRMB").val(formatRMBPrice(_purchaseRMB));//采购人民币
                    }
                    _getrapnet(data.Weight);
                    if (data.PurchaseUSDPerCarat){
                        $("#purchaseUSDPerCarat").val(data.PurchaseUSDPerCarat);//采购每卡$
                    }else {
                        var c_price = calcPercent1Price(data.SourceDiscountReturn, data.SourceDolarPerCarat); //100/1 原退点的美金克拉
                        $("#purchaseUSDPerCarat").val((c_price * (100 + (data.PurchaseDiscountReturn))).toFixed(3));//计算采购每卡$
                    }
//                  if (data.PurchaseUSDPerGrain) {
//                      $("#purchaseUSDPerGrain").val(data.PurchaseUSDPerGrain);//采购总价$
//                  }else {
//                      var g_price = calcPercent1Price(data.SourceDiscountReturn, data.SourceDolarPerGrain); //100/1   原退点的美金粒
//                      $("#purchaseUSDPerGrain").val((g_price * (100 + (data.PurchaseDiscountReturn))).toFixed(3));//计算采购每卡$
//                  }
                    if (data.PurchaseUSDPerGrain) {
                        var g_price = calcPercent1Price(data.SourceDiscountReturn, data.SourceDolarPerGrain); //100/1   原退点的美金粒
                        $("#purchaseUSDPerGrain").val(data.PurchaseUSDPerGrain);//采购总价$
                        $("#purchaseDiscountReturn").val((data.PurchaseUSDPerGrain/g_price-100).toFixed(3));
                    }else {
                        var g_price = calcPercent1Price(data.SourceDiscountReturn, data.SourceDolarPerGrain); //100/1   原退点的美金粒
                        $("#purchaseUSDPerGrain").val((g_price * (100 + (data.PurchaseDiscountReturn))).toFixed(3));//计算采购每卡$
                        $("#purchaseDiscountReturn").val((data.PurchaseUSDPerGrain/g_price-100).toFixed(3));
                    }
                    myApp.hideIndicator();//隐藏加载中

                }
            });
        },
        //新增提交
        addProduct:function(){
            // var params = $("#form_data").serializeArray();
            console.log(TYPE)
            myApp.showPreloader(_("上传中，请稍等!"));
            $("#Category").val($("#data_category span.active").attr("data-value"));
            var finalRes = $('#form_data').serializeArray().reduce(function(result, item){
                if(item.value=="未支付"){//付款
                    item.value="0";
                }else if(item.value=="已支付"){
                    item.value="1";
                }
                result[item.name] = item.value;
                return result;
            }, {})//把提交的数据转为JSON格式
            if(TYPE==1){
                finalRes.Hue='';
                finalRes.Milky='';
            }
            finalRes.Tag=$("#form_Tag").val();
            if(EDITMODE){
                var manageURL="/Team/ModifyDia";
            }else{
                var manageURL = "/Team/AddDia";
                finalRes.UserID = UserID;
            }

            $.ajax({
                type:"POST",
                url:manageURL,
                data:JSON.stringify(finalRes),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                    myApp.hidePreloader();
                    if(EDITMODE){
                        var tipString=_("修改");
                    }else{
                        var tipString=_("新增");
                    }
                    if(_result.result==true){
                        myApp.alert(tipString+_("成功！"));
                    }else{
                        myApp.alert(_result.msginfo);
                    }
                }
            });

        },
        //公共参数
        loadCommon:function(){

            //形状
            var shape='';
            for (var i = 0; i < stock[1].Shape.length; i++) {
                shape +='<option value="'+stock[1].Shape[i][0]+'">'+ _(stock[1].Shape[i][1]) +'</option>';
            }
            $("#data_shape").html(shape);
            //净度
            var clarity='';
            for (var i = 0; i < stock[1].Clarity.length; i++) {
                clarity +='<option value="'+stock[1].Clarity[i][0]+'">'+ _(stock[1].Clarity[i][1]) +'</option>';
            }
            $("#data_clarity").html(clarity);
            //切工
            var cut='';
            for (var i = 0; i < stock[1].Cut.length; i++) {
                cut +='<option value="'+stock[1].Cut[i][0]+'">'+ _(stock[1].Cut[i][1]) +'</option>';
            }
            $("#data_cut").html(cut);

            //抛光
            var polish='';
            for (var i = 0; i < stock[1].Polish.length; i++) {
                polish +='<option value="'+stock[1].Polish[i][0]+'">'+ _(stock[1].Polish[i][1]) +'</option>';
            }
            $("#data_polish").html(polish);
            //对称
            var symmetry='';
            for (var i = 0; i < stock[1].Symmetry.length; i++) {
                symmetry +='<option value="'+stock[1].Symmetry[i][0]+'">'+ _(stock[1].Symmetry[i][1]) +'</option>';
            }
            $("#data_symmetry").html(symmetry);
            //荧光
            var fluorescence='';
            for (var i = 0; i < stock[1].Fluorescence.length; i++) {
                fluorescence +='<option value="'+stock[1].Fluorescence[i][0]+'">'+ _(stock[1].Fluorescence[i][1]) +'</option>';
            }
            $("#data_fluorescence").html(fluorescence);
            //证书类型
            var cert='';
            for (var i = 0; i < stock[1].CertType.length; i++) {
                cert +='<option value="'+stock[1].CertType[i][0]+'">'+ _(stock[1].CertType[i][1]) +'</option>';
            }
            $("#data_cert").html(cert);
            //所在地
            var place='';
            for (var i = 0; i < stock[1].Place.length; i++) {
                place +='<option value="'+stock[1].Place[i][0]+'">'+ _(stock[1].Place[i][1]) +'</option>';
            }
            $("#data_place").html(place);
            //状态
            var status='';
            for(var i=0;i<stock[1].Status.length;i++){
                status+='<option value="'+stock[1].Status[i][0]+'">'+_(stock[1].Status[i][1])+'</option>';
            }
            $("#data_status").html(status);
            //色调
            var hue='';
            for(var i=0;i<stock[1].Hue.length;i++){
                hue+='<option value="'+stock[1].Hue[i][0]+'">'+_(stock[1].Hue[i][1])+'</option>';
            }
            $("#data_hue").html(hue);
            //奶油
            var milky='';
            for(var i=0;i<stock[1].Milky.length;i++){
                milky+='<option value="'+stock[1].Milky[i][0]+'">'+_(stock[1].Milky[i][1])+'</option>';
            }
            $("#data_milky").html(milky);
            //心箭
            var ha='';
            for(var i=0;i<stock[1].HA.length;i++){
                ha+='<option value="'+stock[1].HA[i][0]+'">'+_(stock[1].HA[i][1])+'</option>';
            }
            $("#data_ha").html(ha);
            //肉眼
            var eyeClean='';
            for(var i=0;i<stock[1].EyeClean.length;i++){
                eyeClean+='<option value="'+stock[1].EyeClean[i][0]+'">'+_(stock[1].EyeClean[i][1])+'</option>';
            }
            $("#data_eyeClean").html(eyeClean);
        },
        // 切换类型
        changType:function(type){
            $("#data_process,#data_oiliness").remove();
            //颜色
            var color='';
            for (var i = 0; i < stock[type].Color.length; i++) {
                color +='<option value="'+stock[type].Color[i][0]+'">'+ _(stock[type].Color[i][1]) +'</option>';
            }
            $("#data_color").html(color);
            if(type==0){//白钻



            }else{//1为彩钻

            }

        },
    }
    addForm.init();
})();
//rapnet
function _getrapnet(weight) {
    if ($("#data_color").val() != "" && $("#data_clarity").val() != "") {
        param = {};
        param.Weight = weight;
        param.Color = $("#data_color").val();
        param.Clarity = $("#data_clarity").val();
        param.Shape = $("#data_shape").val();
        getrapnet(param);
    }

}
function formatReceiptStatus(val){
    if(val==0){
        return _("未支付");
    }else if(val==1){
        return _("已支付");
    }
}

function getRecommend(){
    $.ajax({
        url: "/Team/GetRecommend",//提交地址
        type: "POST",//提交方式
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            var result = JSON.parse(result);//eval()解析单个json对象
            if (result.msgcode == true) {
                recommendNum = result.msginfo.length + 1;
                var $remommend; //单个修改推荐显示下拉框
                $remommend = '<option value="0"></option>'
                for (var i = 0; i < result.msginfo.length; i++) {
                    $remommend += '<option value="' + result.msginfo[i].ShortTag + '">' + _(result.msginfo[i].RecommendName) + '</option>';
                }
                $("#form_Tag").html($remommend);

            }
        }
    });
}